package com.changgou.controller;

import com.changgou.file.FastDFSFile;
import com.changgou.util.FastFDSClient;
import entity.Result;
import entity.StatusCode;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@CrossOrigin //跨域
public class FileUploadController {

    /***
     * 文件上传
     * http://localhost:18082/upload   POST
     * @param file:MultipartFile  上传的文件封装对象
     *            MultipartFile.getOriginalFilename()获取文件名字    例如：heheh.jpeg
     *            StringUtils.getFilenameExtension("heheh.jpeg")     值jpeg
     * @return 文件的访问URL
     */
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam(name = "file") MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(filename);
        byte[] bytes = file.getBytes();
        String author = "柯达";

        FastDFSFile dfsFile = new FastDFSFile(filename, bytes, filenameExtension, null, author);

        //调用客户端方法上传文件
        String[] uploadResult = FastFDSClient.upload(dfsFile);
        //拼接访问地址  http://192.168.206.130:8080/group1/M00/00/44/SDFSFDSFSDFSDFSDF.png
        String url = "http://192.168.206.130:8080/" + uploadResult[0] + "/" + uploadResult[1];
        return new Result<String>(true, StatusCode.OK, "上传成功", url);
    }
}
